﻿using System.IO;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using BabyShop.Site.ViewModels;

namespace BabyShop.Site.Exts.ModelBinders
{
    public class JqGridModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            object model = base.BindModel(controllerContext, bindingContext);
            if(bindingContext.ModelType == typeof(JqGridViewModel)) {
                var request = controllerContext.HttpContext.Request;
                string filterStr = request["filters"];
                if (string.IsNullOrEmpty(filterStr)) {
                    foreach (var param in request.Params) {
                        if (param.ToString().ToLower() == "filters") {
                            filterStr = request[param.ToString()];
                            break;
                        }
                    }
                }
                JqGridViewModel jqVM = model as JqGridViewModel;
                if (jqVM == null)
                    return null;
                if (!string.IsNullOrEmpty(filterStr)) {
                    JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
                    jqVM.Filters = jsSerializer.Deserialize<JqGridFilter>(filterStr);
                }
                return jqVM;
            }
            return model;
        }
    }
}